package com.merck.utils;


import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.merck.service.export.GenerateExcelImpl;
import com.merck.service.export.SqlStr;
import org.apache.log4j.Logger;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

public class SendMail {
    private Logger log = Logger.getLogger(SendMail.class);

    public static void sendMail(String to, String cc, String subject, String content, List<File> attachments){
//        log.info("sendMail-----start");
        AmazonS3 s3Client = null;
        String configBucketName = null;
        String configRemoteFileName = null;
        Properties pro = new Properties();

        Properties properties = new Properties();
        InputStream resourceAsStream = null;
        try {
            InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");
            pro.load(in);
            if (in != null) {
                in.close();
            }
            configBucketName =(String) pro.get("config.bucket");
            configRemoteFileName =(String) pro.getProperty("config.remote");
//            resourceAsStream = SendMail.class.getResourceAsStream("/config.properties");
//            properties.load(resourceAsStream);
            s3Client = openS3ClientByEC2();
            GetObjectRequest getObjectRequest = new GetObjectRequest(configBucketName, configRemoteFileName);
            S3Object s3Object = s3Client.getObject(getObjectRequest);
            resourceAsStream = s3Object.getObjectContent();
            properties.load(resourceAsStream);
            if (resourceAsStream != null) {
                resourceAsStream.close();
            }
            // 1.创建邮件对象

            properties.put("mail.smtp.host", "smtpgw.merck.de"); // 指定SMTP服务器
            properties.put("mail.smtp.auth", "false"); // 指定是否需要SMTP验证
            properties.put("mail.smtp.port", "25");
            //properties.put("mail.smtp.socketFactory.class", properties.get("mail.smtp.socketFactory.class"));
//        properties.put("mail.smtp.socketFactory.fallback", properties.get("mail.smtp.socketFactory.fallback"));
//        properties.put("mail.smtp.socketFactory.port", properties.get("mail.smtp.port"));
            Session session = Session.getInstance(properties);
            MimeMessage mimeMessage = new MimeMessage(session);

            /*
             * 2.设置发件人 其中 InternetAddress 的三个参数分别为: 邮箱, 显示的昵称(只用于显示, 没有特别的要求), 昵称的字符集编码
             */

            mimeMessage.setFrom(new InternetAddress((String) properties.get("send.mail.from")));
            /*
             * 3.设置收件人 To收件人 CC 抄送 BCC密送
             */
//            mimeMessage.setRecipient(MimeMessage.RecipientType.TO,
//                    new InternetAddress((String) properties.get("send.mail.to")));
            //增加收件人
//            mimeMessage.addRecipient(MimeMessage.RecipientType.TO,
//                    new InternetAddress("lucas.tong@analyticservice.net"));

          String mailTo =   properties.get("send.mail.to").toString();

            String[] split1 = mailTo.split(",");
            if(split1.length>0){
                if (split1.length==1){
                    mimeMessage.setRecipient(MimeMessage.RecipientType.TO,
                            new InternetAddress(split1[0], split1[0], "UTF-8"));
                }else {
                    mimeMessage.setRecipient(MimeMessage.RecipientType.TO,
                            new InternetAddress(split1[0], split1[0], "UTF-8"));
                    for (int i = 1; i < split1.length; i++) {
                        mimeMessage.addRecipient(MimeMessage.RecipientType.TO,
                                new InternetAddress(split1[i], split1[i], "UTF-8"));
                    }
		/*mimeMessage.addRecipient(MimeMessage.RecipientType.TO,
				new InternetAddress(to, to, "UTF-8"));*/
                }
            }
//抄送
          String mailCc = properties.get("send.mail.cc").toString();
            if (!mailCc.equals("")){
                String[] split2 = mailCc.split(",");
                if (split2.length==1){
                    mimeMessage.setRecipient(MimeMessage.RecipientType.CC,
                            new InternetAddress(split2[0], split2[0], "UTF-8"));
                }else {
                    mimeMessage.setRecipient(MimeMessage.RecipientType.CC,
                            new InternetAddress(split2[0], split2[0], "UTF-8"));
                    for (int i = 1; i < split2.length; i++) {
                        mimeMessage.addRecipient(MimeMessage.RecipientType.CC,
                                new InternetAddress(split2[i], split2[i], "UTF-8"));
                    }
		/*mimeMessage.addRecipient(MimeMessage.RecipientType.TO,
				new InternetAddress(to, to, "UTF-8"));*/
                }
            }




            /* 4.设置标题和内容 */
            mimeMessage.setSubject(subject, "UTF-8");
            mimeMessage.setContent(content, "text/html;charset=UTF-8");
            mimeMessage.setSentDate(new Date());
            //一个Multipart对象包含一个或多个bodypart对象，组成邮件正文
            MimeMultipart multipart = new MimeMultipart();
		/*MimeBodyPart file2 = new MimeBodyPart();
	      DataHandler dataHandler3 = new DataHandler(new FileDataSource("D:\\beigene_server\\excel\\xls\\201903261708020263471.xls"));
	      file2.setDataHandler(dataHandler3);
	      file2.setFileName(MimeUtility.encodeText(dataHandler3.getName()));
	     multipart.addBodyPart(file2);*/
            BodyPart html = new MimeBodyPart();
            html.setContent(content.trim(), "text/html; charset=utf-8");
            multipart.addBodyPart(html);

            mimeMessage.setSentDate(new Date());
            //邮件附件
            if(attachments != null) {
                for(File attachment : attachments) {
                    BodyPart attachmentPart = new MimeBodyPart();
                    DataSource source = new FileDataSource(attachment);
                    attachmentPart.setDataHandler(new DataHandler(source));
                    //避免中文乱码的处理
                    attachmentPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
                    multipart.addBodyPart(attachmentPart);
                }
            }
            mimeMessage.setContent(multipart);

            /* 5.保存邮件 */
            mimeMessage.saveChanges();

            Transport transport = session.getTransport("smtp"); // 获取邮件传输对象
            transport.connect();
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
            transport.close();
//        log.info("sendMail-----end");
            //System.out.println("sendMailServlet-----end");
        }catch(Exception e){
            throw new RuntimeException(e.getMessage());
    }
    }
    public static AmazonS3 openS3ClientByEC2() {
        AmazonS3 s3Client = null;
        try {
            s3Client = AmazonS3ClientBuilder.defaultClient();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return s3Client;
    }

    public static void main(String[] args) {
        System.out.println("开始发邮件");

            List<File> atts = new ArrayList<>();
            File file = new File("temp.xlsx");
            atts.add(file);
            String currentDateAsString = DateUtils.getCurrentDateAsString();
            SendMail.sendMail(null, null, "导出数据任务在 " + currentDateAsString + " 运行结果通知", SqlStr.SUCESS_SEND_CONTENT,atts);

        System.out.println("发邮件结束");
    }
}
